package com.zx.system.block.utils;

import com.zx.common.tools.id.components.IdGeneratorComponent;
import com.zx.common.tools.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 系统模块编号生成工具类
 * 使用ID生成器组件生成全局唯一的ID
 */
@Slf4j
@Component
public class SystemNoUtils {

    private static IdGeneratorComponent idGeneratorComponent;

    /**
     * 获取ID生成器组件实例
     * 延迟初始化，避免在Spring上下文未准备好时就尝试获取Bean
     *
     * @return IdGeneratorComponent实例
     */
    private static IdGeneratorComponent getIdGeneratorComponent() {
        if (idGeneratorComponent == null) {
            idGeneratorComponent = SpringContextUtil.getBean(IdGeneratorComponent.class);
        }
        return idGeneratorComponent;
    }

    /**
     * 生成系统相关ID
     *
     * @return 系统ID
     */
    public static String generateSystemId() {
        try {
            String systemId = getIdGeneratorComponent().generateId();
            // 如果是纯数字ID（雪花算法），则添加SYS前缀
            if (systemId.matches("\\d+")) {
                systemId = "SYS" + systemId;
            }
            // 如果是UUID，则直接使用，避免ID过长
            log.debug("Generated system ID: {}", systemId);
            return systemId;
        } catch (Exception e) {
            log.error("Failed to generate system ID", e);
            throw new RuntimeException("Failed to generate system ID", e);
        }
    }
}